// Decompiled by Jad v1.5.7g. Copyright 2000 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/SiliconValley/Bridge/8617/jad.html
// Decompiler options: packimports(3) fieldsfirst ansi 
// Source File Name:   ESSPO.java

package com.vandagroup.common.po;

import com.vandagroup.common.bean.BaseBean;
import com.vandagroup.common.bean.FormBean;
import com.vandagroup.common.bo.ESSBean;
import com.vandagroup.common.bo.ESSObject;
import com.vandagroup.common.db.ESSDataStoreManager;
import com.vandagroup.common.exp.ESSConnectionGetTimeOutException;
import com.vandagroup.common.exp.ESSException;
import com.vandagroup.common.util.*;
import java.sql.*;
import java.util.Vector;
import org.apache.log4j.Logger;

// Referenced classes of package com.vandagroup.common.po:
//            ESSPLQueryInterface

public abstract class ESSPO extends ESSBean
    implements ESSPLQueryInterface
{

    public static Logger log;
    private String dbName;
    protected int resultSize;
    protected int startPosition;
    protected boolean countable;
    protected int recordCounter;
    private String whereClause;
    protected String orderBy;
    protected String groupBy;
    private ESSBean dataBean;
    private String inputSql;
    static Class class$0; /* synthetic field */

    public ESSPO()
    {
        dbName = null;
        resultSize = 0;
        startPosition = 0;
        countable = true;
        recordCounter = 0;
        whereClause = null;
        orderBy = null;
        groupBy = null;
        inputSql = null;
    }

    public String convert(String val)
    {
        if(val == null || val.equals(""))
            return "";
        else
            return val;
    }

    public Object convert(Object val)
    {
        if(val == null)
            return "";
        else
            return val;
    }

    public String encodeString(String val)
    {
        if(val == null || val.equals(""))
            return "";
        else
            return val;
    }

    public void setWhereClause(String s)
    {
        whereClause = s;
    }

    public String getWhereClause()
    {
        return whereClause;
    }

    public int add()
        throws SQLException, ESSConnectionGetTimeOutException
    {
        int row;
        row = 0;
        String tempSQL = getInsertSQL();
        try
        {
            log.debug("sql = " + genInsertSql());
        }
        catch(Exception e)
        {
            log.debug("sql = " + tempSQL);
            e.printStackTrace();
        }
        PreparedStatement ps = null;
        Connection conn = null;
        try
        {
            if(dbName == null)
                conn = ESSObject.getDataStore().getConnection();
            else
                conn = ESSObject.getDataStore().getConnection(dbName);
            ps = conn.prepareStatement(tempSQL);
            prepareInsertStatement(ps);
            row = ps.executeUpdate();
        }
        catch(SQLException ex)
        {
            log(ex, "Insert error!");
            log.debug("sql = " + tempSQL);
            throw ex;
        }
        catch(Throwable et)
        {
            log.debug("sql = " + tempSQL);
            log.error("Method add Throwable:", et);
        }
        finally
        {
            try
            {
                if(ps != null)
                    ps.close();
            }
            catch(Exception e)
            {
                log.error("Method add Exception:", e);
            }
            try
            {
                if(dbName == null)
                    ESSObject.getDataStore().freeConnection(conn);
                else
                    ESSObject.getDataStore().freeConnection(conn, dbName);
            }
            catch(Exception e)
            {
                log.error("Method add Exception:", e);
            }
        }
        return row;
    }

    public int delete()
        throws SQLException, ESSConnectionGetTimeOutException
    {
        int row;
        row = 0;
        String sql = getDeleteSQL();
        log.debug("sql = " + sql);
        Statement statement = null;
        Connection conn = null;
        try
        {
            conn = dbName == null ? ESSObject.getDataStore().getConnection() : ESSObject.getDataStore().getConnection(dbName);
            statement = conn.createStatement();
            row = statement.executeUpdate(sql);
        }
        catch(SQLException ex)
        {
            log.debug("sql = " + sql);
            log(ex, "Delete error!");
            throw ex;
        }
        finally
        {
            try
            {
                if(statement != null)
                    statement.close();
            }
            catch(Exception exception1) { }
            try
            {
                if(dbName == null)
                    ESSObject.getDataStore().freeConnection(conn);
                else
                    ESSObject.getDataStore().freeConnection(conn, dbName);
            }
            catch(Exception e)
            {
                log.error("Exception:", e);
            }
        }
        return row;
    }

    public int update()
        throws SQLException, ESSConnectionGetTimeOutException
    {
        int row;
        row = 0;
        String sql = getUpdateSQL();
        PreparedStatement ps = null;
        Connection conn = null;
        try
        {
            conn = dbName == null ? ESSObject.getDataStore().getConnection() : ESSObject.getDataStore().getConnection(dbName);
            try
            {
                log.debug("sql = " + genUpdateSql());
            }
            catch(Exception e)
            {
                log.debug("sql = " + sql);
                e.printStackTrace();
            }
            ps = conn.prepareStatement(sql);
            prepareUpdateStatement(ps);
            row = ps.executeUpdate();
        }
        catch(SQLException ex)
        {
            log.error("SQLException :", ex);
            log(ex, "Update error!");
            throw ex;
        }
        finally
        {
            try
            {
                if(ps != null)
                    ps.close();
            }
            catch(Exception e)
            {
                log.debug("Method update Exception:" + e.getStackTrace());
            }
            try
            {
                if(dbName == null)
                    ESSObject.getDataStore().freeConnection(conn);
                else
                    ESSObject.getDataStore().freeConnection(conn, dbName);
            }
            catch(Exception e)
            {
                log.error("Exception:", e);
            }
        }
        return row;
    }

    public int update(String columnName, Object value, boolean isString)
        throws SQLException, ESSConnectionGetTimeOutException
    {
        String sql = "update " + getTableName();
        sql = sql + " set " + columnName + "=";
        if(isString)
            sql = sql + "'" + value + "' ";
        else
            sql = sql + value + " ";
        sql = sql + "where " + whereClause;
        return executeUpdate(sql);
    }

    public int update(String columnName, Object value)
        throws SQLException, ESSConnectionGetTimeOutException
    {
        return update(columnName, value, true);
    }

    public int executeUpdate(String sql)
        throws SQLException, ESSConnectionGetTimeOutException
    {
        int row;
        row = 0;
        Statement statement = null;
        Connection conn = null;
        try
        {
            conn = dbName == null ? ESSObject.getDataStore().getConnection() : ESSObject.getDataStore().getConnection(dbName);
            statement = conn.createStatement();
            row = statement.executeUpdate(sql);
            log.debug("sql=" + sql);
        }
        catch(SQLException ex)
        {
            throw ex;
        }
        finally
        {
            try
            {
                if(statement != null)
                    statement.close();
            }
            catch(Exception exception1) { }
            try
            {
                if(dbName == null)
                    ESSObject.getDataStore().freeConnection(conn);
                else
                    ESSObject.getDataStore().freeConnection(conn, dbName);
            }
            catch(Exception e)
            {
                log.debug("Method ExecuteUpdate Exception:" + e.getStackTrace());
            }
        }
        return row;
    }

    public abstract String getTableName();

    public abstract String getColumnNames();

    public abstract String getInsertValuesString();

    public abstract String getUpdateValuesString();

    public abstract FormBean fetchResult(ResultSet resultset)
        throws SQLException;

    public abstract void prepareInsertStatement(PreparedStatement preparedstatement)
        throws SQLException;

    public abstract void prepareUpdateStatement(PreparedStatement preparedstatement)
        throws SQLException;

    public ESSBean getDataBean()
    {
        return this;
    }

    public void setDataBean(ESSBean dataBean)
    {
        this.dataBean = dataBean;
    }

    public String getDeleteSQL()
    {
        StringBuffer tempSQL = new StringBuffer(256);
        tempSQL.append("DELETE FROM ");
        tempSQL.append(getTableName());
        if(whereClause != null)
        {
            tempSQL.append(" WHERE ");
            tempSQL.append(getWhereClause());
        }
        return tempSQL.toString();
    }

    public String getInsertSQL()
    {
        StringBuffer tempSQL = new StringBuffer(256);
        tempSQL.append("INSERT INTO ");
        tempSQL.append(getTableName());
        tempSQL.append(" (");
        tempSQL.append(getColumnNames());
        tempSQL.append(") ");
        tempSQL.append("VALUES(" + getInsertValuesString() + ") ");
        return tempSQL.toString();
    }

    public String getQuerySQL()
    {
        StringBuffer SQL = new StringBuffer(300);
        SQL.append("SELECT ");
        SQL.append(getColumnNames());
        SQL.append(" FROM ");
        SQL.append(getTableName());
        return SQL.toString();
    }

    public String getUpdateSQL()
    {
        StringBuffer tempSQL = new StringBuffer(256);
        tempSQL.append("UPDATE ");
        tempSQL.append(getTableName());
        tempSQL.append(" SET ");
        tempSQL.append(getUpdateValuesString());
        if(whereClause != null)
        {
            tempSQL.append(" WHERE ");
            tempSQL.append(getWhereClause());
        }
        return tempSQL.toString();
    }

    public FormBean[] retrieve()
        throws SQLException, ESSConnectionGetTimeOutException
    {
        FormBean aformbean[];
        FormBean validatorForms[] = (FormBean[])null;
        String sql = getSql();
        log.debug("sql = " + sql);
        Connection conn = null;
        Statement statement = null;
        ResultSet resultset = null;
        try
        {
            conn = dbName == null ? ESSObject.getDataStore().getConnection() : ESSObject.getDataStore().getConnection(dbName);
            statement = conn.createStatement();
            resultset = statement.executeQuery(sql);
            Vector list = new Vector();
            for(; resultset.next(); list.add(fetchResult(resultset)));
            validatorForms = new FormBean[list.size()];
            list.copyInto(validatorForms);
            aformbean = validatorForms;
        }
        finally
        {
            if(resultset != null)
                try
                {
                    resultset.close();
                }
                catch(SQLException sqlexception) { }
            if(statement != null)
                try
                {
                    statement.close();
                }
                catch(SQLException sqlexception1) { }
            try
            {
                if(dbName == null)
                    ESSObject.getDataStore().freeConnection(conn);
                else
                    ESSObject.getDataStore().freeConnection(conn, dbName);
            }
            catch(Exception e)
            {
                log.error("Exception:", e);
            }
        }
        return aformbean;
    }

    public FormBean retrieveForm()
        throws SQLException, ESSConnectionGetTimeOutException
    {
        FormBean validatorForms[] = retrieve();
        if(validatorForms != null && validatorForms.length > 0)
            return validatorForms[0];
        else
            return null;
    }

    public Result retrieveResult()
        throws SQLException, ESSConnectionGetTimeOutException
    {
        Result result1;
        FormBean validatorForms[] = (FormBean[])null;
        String sql = getSql();
        Connection conn = null;
        Statement statement = null;
        ResultSet resultset = null;
        countable = false;
        try
        {
            conn = dbName == null ? ESSObject.getDataStore().getConnection() : ESSObject.getDataStore().getConnection(dbName);
            statement = conn.createStatement();
            resultset = statement.executeQuery(sql);
            Vector list = new Vector();
            int currsorPosition = 0;
            while(resultset.next()) 
            {
                if(currsorPosition < startPosition)
                {
                    currsorPosition++;
                    continue;
                }
                if(resultSize > 0 && currsorPosition - startPosition == resultSize)
                {
                    currsorPosition++;
                    countable = true;
                    break;
                }
                list.add(fetchResult(resultset));
                currsorPosition++;
            }
            while(countable && resultset.next()) 
                currsorPosition++;
            recordCounter = currsorPosition;
            validatorForms = new FormBean[list.size()];
            list.copyInto(validatorForms);
            Result result = new Result();
            result.setForms(validatorForms);
            result.setCounter(recordCounter);
            result.setStartPosition(startPosition);
            if(resultSize > 0)
                result.setResultSize(resultSize);
            result1 = result;
        }
        finally
        {
            if(resultset != null)
                try
                {
                    resultset.close();
                }
                catch(SQLException ex)
                {
                    log.debug("Method retrieveResult SQLException:" + ex.getStackTrace());
                }
            if(statement != null)
                try
                {
                    statement.close();
                }
                catch(SQLException ex)
                {
                    log.debug("Method retrieveResult SQLException:" + ex.getStackTrace());
                }
            try
            {
                if(dbName == null)
                    ESSObject.getDataStore().freeConnection(conn);
                else
                    ESSObject.getDataStore().freeConnection(conn, dbName);
            }
            catch(Exception e)
            {
                log.debug("Method retrieveResult Exception:" + e.getStackTrace());
            }
        }
        return result1;
    }

    public String getDbName()
    {
        return dbName;
    }

    public void setDbName(String dbName)
    {
        this.dbName = dbName;
    }

    public String getGroupBy()
    {
        return groupBy;
    }

    public String getOrderBy()
    {
        return orderBy;
    }

    public void setGroupBy(String groupBy)
    {
        this.groupBy = groupBy;
    }

    public void setOrderBy(String orderBy)
    {
        this.orderBy = orderBy;
    }

    public void setResultSize(int size)
    {
        resultSize = size;
    }

    public void setStartPosition(int startPos)
    {
        startPosition = startPos;
    }

    public void setResultPage(int size, int page)
    {
        if(page > 0 && size > 0)
        {
            setResultSize(size);
            setStartPosition(size * (page - 1));
        }
    }

    public String getSql()
    {
        String sql = getQuerySQL();
        if(whereClause != null && whereClause.length() > 0)
            sql = sql + " WHERE " + whereClause;
        if(groupBy != null && groupBy.length() > 0)
            sql = sql + " GROUP BY " + groupBy;
        if(orderBy != null && orderBy.length() > 0)
            sql = sql + " ORDER BY " + orderBy;
        return encodeString(sql);
    }

    public void prepareSetInt(PreparedStatement ps, int i, Integer v)
        throws SQLException
    {
        if(v != null)
            ps.setInt(i, v.intValue());
        else
            ps.setNull(i, 4);
    }

    public BaseBean[] query()
        throws SQLException, ESSConnectionGetTimeOutException, Exception
    {
        BaseBean baseBeans[];
        baseBeans = (BaseBean[])null;
        String sql = inputSql == null ? getSql() : inputSql;
        Connection conn = null;
        Statement statement = null;
        ResultSet resultset = null;
        ResultSetMetaData rsmd = null;
        try
        {
            conn = dbName == null ? ESSObject.getDataStore().getConnection() : ESSObject.getDataStore().getConnection(dbName);
            statement = conn.createStatement();
            
            log.debug("query sql is :" + sql) ;
            
            resultset = statement.executeQuery(sql);
            rsmd = resultset.getMetaData();
            checkColumnName(rsmd);
            int columnCount = rsmd.getColumnCount();
            Vector list = new Vector();
            BaseBean baseBean;
            for(; resultset.next(); list.add(baseBean))
            {
                baseBean = new BaseBean();
                baseBean.setLength(columnCount);
                for(int j = 1; j <= columnCount; j++)
                    baseBean.put(rsmd.getColumnName(j).toUpperCase(), resultset.getObject(j) == null ? "" : convert(resultset.getObject(j)));

            }

            baseBeans = new BaseBean[list.size()];
            list.copyInto(baseBeans);
        }
        catch(SQLException ex)
        {
            log.error("Method query SQLException:", ex);
            throw ex;
        }
        finally
        {
            if(resultset != null)
                try
                {
                    resultset.close();
                }
                catch(SQLException sqlexception) { }
            if(statement != null)
                try
                {
                    statement.close();
                }
                catch(SQLException sqlexception1) { }
            try
            {
                if(dbName == null)
                    ESSObject.getDataStore().freeConnection(conn);
                else
                    ESSObject.getDataStore().freeConnection(conn, dbName);
            }
            catch(Exception e)
            {
                log.debug("Method query Exception:" + e.getStackTrace());
            }
        }
        return baseBeans;
    }

    public BaseBean[] query(String sql)
        throws SQLException, ESSConnectionGetTimeOutException, Exception
    {
    	log.debug("query sql is:" + sql) ;
    	
        inputSql = sql;
        return query();
    }

    public BaseBean queryBean()
        throws SQLException, ESSConnectionGetTimeOutException, Exception
    {
        BaseBean baseBeans[] = query();
        if(baseBeans != null && baseBeans.length > 0)
            return baseBeans[0];
        else
            return null;
    }

    public BaseBean queryBean(String sql)
        throws SQLException, ESSConnectionGetTimeOutException, Exception
    {
        inputSql = sql;
        BaseBean baseBeans[] = query();
        if(baseBeans != null && baseBeans.length > 0)
            return baseBeans[0];
        else
            return null;
    }

    public Result queryResult()
        throws SQLException, ESSConnectionGetTimeOutException, Exception
    {
        Result result;
        result = new Result();
        BaseBean baseBeans[] = (BaseBean[])null;
        String sql = inputSql == null ? getSql() : inputSql;
        Connection conn = null;
        Statement statement = null;
        ResultSet resultset = null;
        ResultSetMetaData rsmd = null;
        countable = false;
        try
        {
            if(dbName == null)
                conn = ESSObject.getDataStore().getConnection();
            else
                conn = ESSObject.getDataStore().getConnection(dbName);
            statement = conn.createStatement();
            resultset = statement.executeQuery(sql);
            rsmd = resultset.getMetaData();
            checkColumnName(rsmd);
            int columnCount = rsmd.getColumnCount();
            String cns = "";
            for(int j = 1; j <= columnCount; j++)
            {
                if(j > 1)
                    cns = cns + ",";
                cns = cns + rsmd.getColumnName(j);
            }

            result.setColumnNames(cns);
            Vector list = new Vector();
            int currsorPosition = 0;
            while(resultset.next()) 
            {
                if(currsorPosition < startPosition)
                {
                    currsorPosition++;
                    continue;
                }
                if(resultSize > 0 && currsorPosition - startPosition == resultSize)
                {
                    currsorPosition++;
                    countable = true;
                    break;
                }
                BaseBean baseBean = new BaseBean();
                baseBean.setLength(columnCount);
                for(int j = 1; j <= columnCount; j++)
                    baseBean.put(rsmd.getColumnName(j).toUpperCase(), resultset.getObject(j) == null ? "" : convert(resultset.getObject(j)));

                list.add(baseBean);
                currsorPosition++;
            }
            while(countable && resultset.next()) 
                currsorPosition++;
            recordCounter = currsorPosition;
            baseBeans = new BaseBean[list.size()];
            list.copyInto(baseBeans);
            result.setBaseBeans(baseBeans);
            result.setCounter(recordCounter);
            result.setStartPosition(startPosition);
            if(resultSize > 0)
                result.setResultSize(resultSize);
        }
        catch(SQLException ex)
        {
            log.debug("sql = " + sql);
            log.debug("Method queryResult SQLException:" + ex.getStackTrace());
            throw ex;
        }
        finally
        {
            if(resultset != null)
                try
                {
                    resultset.close();
                }
                catch(SQLException sqlexception) { }
            if(statement != null)
                try
                {
                    statement.close();
                }
                catch(SQLException sqlexception1) { }
            try
            {
                if(dbName == null)
                    ESSObject.getDataStore().freeConnection(conn);
                else
                    ESSObject.getDataStore().freeConnection(conn, dbName);
            }
            catch(Exception e)
            {
                log.debug("Method queryResult Exception:" + e.getStackTrace());
            }
        }
        return result;
    }

    public Result queryResult(String sql)
        throws SQLException, ESSConnectionGetTimeOutException, Exception
    {
        inputSql = sql;
        return queryResult();
    }

    public void checkColumnName(ResultSetMetaData rsmd)
        throws SQLException, Exception
    {
        Vector colNames = new Vector();
        for(int m = 1; m <= rsmd.getColumnCount(); m++)
        {
            if(colNames.contains(rsmd.getColumnName(m)))
                throw new ESSException("�����SQL�����������У����д���SQL��䣡");
            colNames.add(rsmd.getColumnName(m).toUpperCase());
        }

    }

    public String queryKey(String sql)
        throws SQLException, ESSConnectionGetTimeOutException, Exception
    {
        String rtn;
        Connection conn = null;
        Statement statement = null;
        ResultSet resultset = null;
        ResultSetMetaData rsmd = null;
        rtn = "'-1'";
        try
        {
            conn = dbName == null ? ESSObject.getDataStore().getConnection() : ESSObject.getDataStore().getConnection(dbName);
            statement = conn.createStatement();
            
            log.debug(" query sql is :" + sql) ;
            
            resultset = statement.executeQuery(sql);
            rsmd = resultset.getMetaData();
            checkColumnName(rsmd);
            int columnCount = rsmd.getColumnCount();
            while(resultset.next()) 
                rtn = rtn + ",'" + resultset.getString(1) + "'";
        }
        catch(SQLException ex)
        {
            log.debug("Method query SQLException:", ex);
            throw ex;
        }
        finally
        {
            if(resultset != null)
                try
                {
                    resultset.close();
                }
                catch(SQLException sqlexception) { }
            if(statement != null)
                try
                {
                    statement.close();
                }
                catch(SQLException sqlexception1) { }
            try
            {
                if(dbName == null)
                    ESSObject.getDataStore().freeConnection(conn);
                else
                    ESSObject.getDataStore().freeConnection(conn, dbName);
            }
            catch(Exception e)
            {
                log.debug("Method query Exception:", e);
            }
        }
        return rtn;
    }

    public abstract FormBean getFormBean();

    public int getfiledNum()
    {
        return getUpdateValuesString().split(",").length;
    }

    public String genUpdateSql()
        throws Exception
    {
        FormBean bean = getFormBean();
        String sql = "update " + getTableName() + " set ";
        String rows[] = getColumnNames().split(",");
        Object value = null;
        for(int i = 0; i < rows.length; i++)
        {
            if(i > 0)
                sql = sql + ",";
            value = Paras.getProperty(bean, rows[i]);
            sql = sql + rows[i] + "=";
            sql = sql + toSqlValue(value);
        }

        sql = sql + " where " + whereClause;
        return sql;
    }

    public String genInsertSql()
        throws Exception
    {
        FormBean bean = getFormBean();
        String sql = "insert into " + getTableName() + " (" + getColumnNames() + ") values(";
        String rows[] = getColumnNames().split(",");
        Object value = null;
        for(int i = 0; i < rows.length; i++)
        {
            if(i > 0)
                sql = sql + ",";
            value = Paras.getProperty(bean, rows[i]);
            sql = sql + toSqlValue(value);
        }

        sql = sql + ")";
        return sql;
    }

    private Object toSqlValue(Object value)
    {
        if(value == null)
            return null;
        if(value instanceof String)
            return "'" + value + "'";
        else
            return value;
    }

    static 
    {
        log = LogUtil.getLogger(com.vandagroup.common.po.ESSPO.class);
    }
}
